package com.kusiri.kframework.salesforce.ui.component
{
	import com.kusiri.kframework.model.IKfValueObjectList;
	import com.kusiri.kframework.model.KfValueObjectListChangedEvent;
	import com.kusiri.kframework.model.kfvalueobjectlistchangedevent.IKfValueObjectListOperation;
	import com.kusiri.kframework.model.kfvalueobjectlistchangedevent.KfValueObjectListAdd;
	import com.kusiri.kframework.model.kfvalueobjectlistchangedevent.KfValueObjectListRemove;
	import com.kusiri.kframework.model.kfvalueobjectlistchangedevent.KfValueObjectListUpdate;
	import com.kusiri.kframework.salesforce.model.KfSalesforceModel;
	import com.kusiri.kframework.salesforce.model.SObject;
	import com.kusiri.kframework.salesforce.model.valueobjectlist.ISObjectList;
	import com.kusiri.kframework.salesforce.ui.SObjectAccordion;
	import com.kusiri.kframework.ui.KfUiComponent;
	
	import mx.collections.ArrayCollection;
	import mx.core.IFlexDisplayObject;

	public class KfSObjectAccordion extends KfUiComponent implements IKfSObjectAccordion
	{
		private var _valueObjectList : ISObjectList; 
		
		public function get valueObjectList() : ISObjectList
		{
			return _valueObjectList;
		}
		
		public function set valueObjectList( valueObjectList : ISObjectList ) : void
		{
			_valueObjectList = valueObjectList;
		} 
		
		private var self : KfSObjectAccordion;
		
		/**
		 * This is is the layout
		 */
		private var uiComponent : SObjectAccordion = new SObjectAccordion(); 
		
		public function KfSObjectAccordion()
		{
			super();
			self = this;
		}
	
		/**
		 * Get the Flex UI Component
		 */
		override public function get __uiComponent() : IFlexDisplayObject
		{
			return uiComponent;
		}

		/**
		 * Remove event listeners, etc.
		 */
		override public function __deactivate() : void
		{
			valueObjectList.removeEventListener(KfValueObjectListChangedEvent.EVENT_NAME,onListChange);
		}

		public function onListChange(event : KfValueObjectListChangedEvent) : void
		{
			var op : IKfValueObjectListOperation;
			for each ( op in event.operations)
			{
				// TODO: Move these as functions into the accordion
				if (op is KfValueObjectListAdd)
				{
					uiComponent.addSObject(op.valueObject as SObject, op.index);
				}
				else if (op is KfValueObjectListRemove)
				{
					uiComponent.removeSObject(op.index);
				}
				else // update
				{
					uiComponent.moveSObject((op as KfValueObjectListUpdate).oldIndex, op.index);
				}
			}
		}

		/**
		 * Tell the UI Component to load its data.
		 */
		override public function __initializeComponent(onSuccess : Function, onFail : Function) : void
		{
			valueObjectList.addEventListener(KfValueObjectListChangedEvent.EVENT_NAME, onListChange);
				
			uiComponent.sobjects = new ArrayCollection(valueObjectList.valueObjects);
			uiComponent.valueObjectList = valueObjectList;
			uiComponent.model = valueObjectList.model as KfSalesforceModel; 
			uiComponent.sobjectType = valueObjectList.type;
			uiComponent.showButtonBar = true;
			onSuccess(this);
		}
		
	}
}